package com.cn.wanxi.message.controller;

import com.cn.wanxi.message.domain.Result;
import com.cn.wanxi.message.domain.User;
import com.cn.wanxi.message.utils.ParamNameUtil;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @ClassName UserController
 * @Description TODO
 * @Author JiJiang
 * @Date 2022/10/7 22:57
 * @Version 1.0
 */
@RestController
@CrossOrigin
@RequestMapping("/user")
public class UserController {


    @Autowired
    private RedisTemplate redisTemplate;

    @GetMapping("/friends")
    public Result findFriends(String username) {

        if (Strings.isEmpty(username)) {

            return Result.getResult("error-noLogin");
        }
        //用于保存已经登录的用户
        List<User> loginFriendList = new ArrayList<>();

        User tmpUser = null;
        //遍历所有的用户，将已经登录的用户添加到用户表
        for (int i = 0; i < ParamNameUtil.USERNAME_ALL.length; i++) {

            //如果遍历到了自己，直接跳过
            if (ParamNameUtil.USERNAME_ALL[i].equals(username)) {
                continue;
            }

            tmpUser = new User();

            tmpUser.setUsername(ParamNameUtil.USERNAME_ALL[i]);

            //如果遍历到的当前用户已经登录
            if (!Objects.isNull(redisTemplate.opsForValue().get(ParamNameUtil.REDIS_LOGIN_USER_NAME +
                    ParamNameUtil.USERNAME_ALL[i]))) {
                tmpUser.setOnlineStatus(1);
                loginFriendList.add(tmpUser);
                continue;
            }
            tmpUser.setOnlineStatus(0);
            loginFriendList.add(tmpUser);
        }

        return Result.getResult("success", loginFriendList);

    }

}
